// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
  const { openid, avatarUrl, nickName } = event
  if (!openid || !avatarUrl || !nickName) {
    return { code: 1, msg: '参数不完整' }
  }
  try {
    // 如果已存在则更新，否则插入
    const users = db.collection('users')
    const res = await users.where({ openid }).get()
    if (res.data.length > 0) {
      await users.where({ openid }).update({
        data: { avatarUrl, nickName }
      })
    } else {
      await users.add({
        data: { openid, avatarUrl, nickName }
      })
    }
    return { code: 0, msg: 'success' }
  } catch (e) {
    return { code: 2, msg: '数据库操作失败', error: e }
  }
} 